<?php

namespace App\Models\Cruise;

use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Cache;

class CruiseCheckDetailModel extends BaseModel
{
    use KfUid, KfSoftDeletes;

    protected $table    = 'cruise_check_details';
    protected $fillable = [
        'code',
        'orderId',
        'taskId',
        'sysTemplate',
        'checkType',
        'dealUid',
        'dealName',
        'companyId',
        'companyName',
        'failNum',
        'totalScore',
        'successScore',
        'reportResult',
        'actualScore',
        'veto',
        'qualityScore',
        'submitTime',
        'isSignature',
        'templateType',
        'createdByUid',
        'isDeleted',
        'templateId',
        'taskName',
        'selfAuditErrorNum',
        'firstSaveTime',
    ];

    public function cruiseOrderRel(): HasOne
    {
        return $this->hasOne(CruiseOrderModel::class, 'id', 'orderId');
    }

    public function cruiseTaskRel(): HasOne
    {
        return $this->hasOne(CruiseCheckTaskModel::class, 'id', 'taskId');
    }

    public function templateRel(): HasOne
    {
        return $this->hasOne(CruiseTemplateModel::class, 'id', 'templateId');
    }

    public static function getDataByOrderId(int $orderId)
    {
        return self::query()->where('orderId', $orderId)->first();
    }

    const CHECK_TYPE_COMMON      = 0;
    const CHECK_TYPE_INSIDE      = 1;
    const CHECK_TYPE_THIRD_PARTY = 2;

    const CHECK_TYPE_MAPPING = [
        self::CHECK_TYPE_COMMON      => '常规',
        self::CHECK_TYPE_INSIDE      => '内部',
        self::CHECK_TYPE_THIRD_PARTY => '三方',
    ];

    const REPORT_RESULT_INIT        = 0;
    const REPORT_RESULT_QUALIFIED   = 1;
    const REPORT_RESULT_UNQUALIFIED = 2;
    const REPORT_RESULT_CANCEL      = 3;

    const REPORT_RESULT_MAPPING = [
        self::REPORT_RESULT_INIT        => '进行中', // 初始化
        self::REPORT_RESULT_QUALIFIED   => '合格',
        self::REPORT_RESULT_UNQUALIFIED => '不合格',
        self::REPORT_RESULT_CANCEL      => '已作废',
    ];

    const VETO_ON  = 0;
    const VETO_OFF = 1;

    const VETO_MAPPING = [
        self::VETO_ON  => '正常',
        self::VETO_OFF => '被否决',
    ];

    /**
     * 关联违约函
     * @return HasMany
     */
    public function cruiseCheckAgainst(): HasMany
    {
       return $this->hasMany(CruiseCheckAgainstModel::class, 'cruiseCheckDetailId', 'id');
    }

    /**
     * 关联整改单
     * @return HasMany
     */
    public function cruiseCheckRectify(): HasMany
    {
        return $this->hasMany(CruiseCheckRectifyModel::class, 'cruiseCheckDetailId', 'id');
    }

    /**
     * 关联异常单
     * @return hasOne
     */
    public function cruiseCheckErrorRel(): hasOne
    {
       return $this->hasOne(CruiseCheckErrorModel::class, 'cruiseCheckDetailId', 'id');
    }

    public function cruiseCheckSelfDetailRel(): HasOne
    {
        return $this->hasOne(CruiseCheckSelfDetailModel::class, 'cruiseOrderId', 'orderId');
    }

    public function processRel(): HasMany
    {
        return $this->hasMany(CruiseOrderProcessModel::class, 'cruiseOrderId', 'orderId');
    }

    //与整改单关联
    const RECTIFY_STATUS_WITH_NOT_NEED = 0;  //无需整改
    const RECTIFY_STATUS_RECTIFIED     = 1;  //待整改
    const RECTIFY_STATUS_FINISH        = 2;  //已完成

    /**
     * 获取巡检人列表
     * @param int $templateType
     * @return array
     */
    public static function dealUidList(int $templateType): array
    {
        return Cache::remember("CruiseCheckDetail_dealUidList:{$templateType}", 120, function () use ($templateType) {
            $userIds = self::query()
                ->where('templateType', $templateType)
                ->where('dealUid', '!=', 0)
                ->select('dealUid as id')
                ->distinct()
                ->get()
                ->pluck('id')
                ->toArray();

            if (!$userIds) {
                return [];
            }

            return collect((new RmsUserApi())->getUserInfoByIds($userIds, ['id', 'username'])['data'] ?? [])
                ->map(function ($item) {
                return [
                    'id' => $item['id'],
                    'name' => $item['username'],
                ];
            })->toArray();
        });
    }
}
